#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        int n=grid.size();
        if (n==0) return 0;
        int m=grid[0].size();
        if (m==0) return 0;
        vector<vector<int> > f(grid);
        for (int j=1;j<m;j++) f[0][j]+=f[0][j-1];
        for (int i=1;i<n;i++) {
            f[i][0]+=f[i-1][0];
            for (int j=1;j<m;j++)
                f[i][j]+=min(f[i-1][j], f[i][j-1]);
        }
        return f[n-1][m-1];
    }
};
